package com.mccree.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问，功能页只有有权限的人才能访问
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //没有权限会到登录页,自定义登录页
        http.formLogin().loginPage("/toLogin")
                .usernameParameter("username")//这里需跟前端传递的参数name保持一致
                .passwordParameter("password")
                .loginProcessingUrl("/login");//这里交给security处理，否则需跟自定义请求同名

        //注销
        http.logout().logoutSuccessUrl("/");
        //注销时报404是因为springboot默认防止csrf跨站请求伪造，
        // 因为会产生安全问题，可以改成post提交或者手动关闭csrf
        http.csrf().disable();
        //开启记住我
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证
    //在springSecurity5中，新增了很多加密方式，且必须加密！
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("mccree").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and().withUser("genji").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and().withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }
}
